package top.healthylife.service.impl;/*
 *@Author GaoZeXi
 *@Created time 2020/4/10 0:17
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;
import top.healthylife.constant.RedisConstant;
import top.healthylife.domain.Setmeal;
import top.healthylife.entity.PageResult;
import top.healthylife.entity.QueryPageBean;
import top.healthylife.mapper.SetmealMapper;
import top.healthylife.service.SetmealService;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@PropertySource("classpath:freemarker.properties")
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 从属性文件中读取要生成的html对应的目录 ,使用spring 注解配置 +spel表达式的方式 读取properties的属性值
     */
    //@Value("${out_put_path}")

    private String outPutPath="D:/develop/IdeaProjects/Demo-myhealth/health_parent/health_mobile/src/main/webapp/pages";

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize =  queryPageBean.getPageSize();
        //开启分页
        PageHelper.startPage(currentPage,pageSize);
        String queryString  = queryPageBean.getQueryString();
        Page<Setmeal> page = setmealMapper.selectByCondition(queryString);
        System.out.println("setmeal:总记录=============="+page.getTotal());
        System.out.println("setmeal:结果集=============="+page.getResult());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealMapper.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealMapper.findById(id);
    }

    /**
     * 查询预约表中 套餐占比情况
     * @return
     */
    @Override
    public List<Map<String, Object>> findSetmealInOrder() {
        return setmealMapper.findSetmealInOrder();
    }

    @Override
    public List<Map<String, Object>> getHotSetmeals() {
        return  setmealMapper.getHotSetmeals();
    }

    /**
     * 新增套餐,同时关联检查组
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //先添加到t_setmeal表中,然后拿到自动生成的id ,将id,checkgroupIds添加到关联表中
        setmealMapper.add(setmeal);
        if(checkgroupIds !=null && checkgroupIds.length>0){
            Integer setmeal_id =setmeal.getId();
            setSetmealAndCheckGroup(setmeal_id,checkgroupIds);
        }
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_VALUED_PIC_RESOURCES,setmeal.getImg());
        //新增套餐后 重新生成静态页面
        generateMobileStaticHtml();
    }



    /**
     * fixme 有问题
     * 关联检查组
     * @param setmeal_id
     * @param checkgroupIds
     */
    private void setSetmealAndCheckGroup(Integer setmeal_id, Integer[] checkgroupIds) {
        if(checkgroupIds !=null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmeal_id",setmeal_id);
                map.put("checkgroup_id",checkgroupId);
                setmealMapper.setSetmealAndCheckGroup(map);
            }
        }
    }

    /**
     * 生成当前方法所需的静态页面
     */
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealMapper.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    /**
     * 生成套餐列表静态页面
     * @param list
     */
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    /**
     * 生成套餐详情静态页面（可能有多个）
     * @param list
     */
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap(16);
            map.put("setmeal",setmealMapper.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    /**
     * 通用的方法，用于生成静态页面
     * @param templateName
     * @param htmlPageName
     * @param map
     */
    public void generteHtml(String templateName,String htmlPageName,Map map){
        //获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            FileOutputStream fos = new FileOutputStream(new File(outPutPath + "/" + htmlPageName));
            Writer out = new OutputStreamWriter(fos,"utf-8");
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
